package cn.edu.swu.dbcp.utils;

import cn.edu.swu.dbcp.book.Book;

import java.util.List;

public class HtmlHelper {

    public static String warpHtml(String content) {
        String template = "<html>\n" +
                "    <head>\n" +
                "      <meta charset=\"utf-8\">\n" +
                "      <title>西大网上书城</title>\n" +
                "      <link rel=\"stylesheet\" href=\"../css/bookstore.css\" />\n" +
                "    </head>\n" +
                "<body>\n" +
                "    <center>\n" +
                "        <br><h1>欢迎访问西大网上书城</h1>\n" +
                "        <div>\n" +
                "            <a href=\"./add_book.html\"> 添加图书 </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n" +
                "            <a href=\"./books\"> 显示图书 </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n" +
                "            <a href=\"./logout\">退出登录 </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n" +
                "        </div>\n" +
                "        <br>\n" +
                "        <form action=\"./searchbook\" method=\"get\">\n" +
                "            <input type=\"text\" name=\"content\"> &nbsp;&nbsp;&nbsp; <input type=\"submit\" value=\"查询\">\n" +
                "        </form>\n" +
                "        %s\n" +
                "    </center>\n" +
                "</body>\n" +
                "</html>";
        return String.format(template,content);
    }

    /**
     *  将传入的图书列表转换成 html 的表格
     *
     */
    public static String buildBooksTable(List<Book> books){
        StringBuilder sb = new StringBuilder();
        sb.append("<table class ='tb-book'>");
        sb.append("<tr>")
                .append("<th>编号</th><th>书名</th><th>价格</th><th>图片</th><th>选项</th><th>选项</th>")
                .append("</tr>");
        String template = "<tr>" +
                "<td align='center'>%s</td>" +
                "<td align='center'>%s</td>" +
                "<td align='center'>%s</td>" +
                "<td align='center'>%s</td>" +
                "<td align='center'><a href='./deletebook?id=%s'>删除</a></td>" +
                "<td align='center'><a href='./updatebook?id=%s'>修改</a></td>" +
                "</tr>";
    // todo :修改表格，使之正常显示图片

        for (Book book : books){
            sb.append(String.format(template,
                    book.getId(), book.getName(), book.getPrice(),
                    (book.getPicture() == null ? "" : String.format("<img src='../upload/%s' width='80px'/>",book.getPicture())),
                    book.getId(),book.getId()
            ));
        }

        sb.append("</table>");
        return sb.toString();
    }
}
